import requests
from lxml import etree
import uuid
import time

cache_list = []
cache_map =  {}
cache_list_type={}
type_list = [
    {"id": 1, "name": "罗湖","urlName":"luohu"},
    {"id": 2, "name": "福田","urlName":"futian"},
    {"id": 3, "name": "南山","urlName":"nanshan"},
    {"id": 4, "name": "龙岗","urlName":""},
    {"id": 5, "name": "宝安","urlName":""},
    {"id": 6, "name": "西乡","urlName":""},
    {"id": 7, "name": "鬼地方","urlName":""},
]

house_id = 1;

class ImageShare():
    def __init__(self):
        pass


    def run(self):
        global  house_id;
        house_id = 1;

        for type in type_list:
            urlName = type.get("urlName")
            if urlName:
                name = type["name"]
                print("%s 的房屋信息开始+++++++++++++++++++++++++++"%name)
                self.url_handle(urlName,type)


    def url_handle(self,urlName,type):
        url_root = "https://sz.zu.anjuke.com/fangyuan/"+urlName;
        url_root = url_root+"/p%s/"
        for i in range(1, 3):
            print("开始爬去房屋信息第 %s 页" % i)
            self.startUrl(url_root % i,type)

    def startUrl(self,url,type):
        global house_id

        root_html = self.send(url)
        etree_html = etree.HTML(root_html)
        hoseLists = etree_html.xpath('//div[contains(@class,"zu-itemmod")]')
        type_id = type.get("id")
        for hoseElement in hoseLists:
            house = {}
            addressElement = hoseElement.xpath('.//address[@class="details-item"]')[0]
            address = " ".join(addressElement.xpath("string()").split())
            title = hoseElement.xpath('.//h3')[0].xpath("string()").strip()
            src240 = hoseElement.xpath('.//a[@class="img"]/img')[0].attrib.get("src")
            imgUrl = src240.replace("240x180m","600x450c")
            house["address"] = address
            house["title"] = title
            house["imgUrl"] = imgUrl
            house["url"] = hoseElement.attrib["link"]
            house["id"] = house_id
            cache_map[house_id] = house
            house_id = house_id + 1
            cache_list.append(house)


            house_type_obj = cache_list_type.get(type_id)
            if not house_type_obj:
                house_type_obj = cache_list_type[type_id] = []
            house_type_obj.append(house)

    def send(self,url):
        headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
        res= requests.get(url=url,headers=headers)
        return res.content.decode("utf8")


    def getInByType(self,type):
        if type == 0:
            return cache_list
        else:
            return cache_list_type.get(type)


    def spider_getHouseInfo(self,url):
        res = self.send(url)
        etree_html = etree.HTML(res)
        imgs = etree_html.xpath("//div[@id='room_pic_wrap']/div[@class='img_wrap']/img/@data-src")
        result = {}
        result["images"] = imgs
        return result

    def getHoserInfo(self,id):
         houseObj = cache_map.get(id)
         if not houseObj:
             return None

         info = houseObj.get("info")
         if not info:
            url = houseObj.get("url")
            info_new = self.spider_getHouseInfo(url)
            info = houseObj["info"] = info_new
         return houseObj

    def getComment(self,id,start,end):
        house = cache_map[id]
        if not house:
            return None
        comments = house.get("comment",[])
        return comments[start:end]


    def setComment(self, id, name, context):
        house = cache_map[id]

        comments = house.get("comment", None)
        if not comments:
            house["comment"] = comments = []

        if not name:
            name = "匿名用户"

        id = str(uuid.uuid1())

        comment = {
            "name": name,
            "context": context,
            "time": time.strftime('%Y-%m-%d %H:%M:%S'),
            "id": id
        }
        comments.insert(0, comment)
        return comment






